import React from 'react'
import { Table, Icon, Modal, Popconfirm, Button, Message, Row, Col } from 'antd';
import api from '../../../api/role';
import { jsonToTree, jsonToTreeByRoot } from "../../../utils/tools";
import PanelBox from '../../../components/PanelBox';
import { WrappedRegistrationForm, ManageRoleForm } from '../../Form/Role';
import './index.less'

export default class TablePage extends React.Component {
  state = {
    resData: [],
    title: "创建角色",
    loading: false,
    checkedKeys: [],
    expandRows: [],
    pagination: false,
    defaultExpandAllRows: true,
    showModal: false,
  };


  columns = [{
    title: '名称',
    dataIndex: 'name',
    key: 'name',
    width: '25%',
  }, {
    title: '英文名称',
    dataIndex: 'enname',
    key: 'enname',
    width: '25%',
  }, {
    title: '状态',
    dataIndex: 'useable',
    key: 'useable',
    width: '25%',
    render: (text, record, index) => {
      switch (record.useable) {
        case '0':
          return '禁用';
        case '1':
          return '启用';
        default:
          return '禁用';
      }
    },
  }, {
    title: '操作',
    dataIndex: 'action',
    render: (text, record) => (
      <span>
        <a href="javascript:void(0)" onClick={this.create.bind(this, "create", record)} >添加</a>
        <span className="ant-divider" />
        <a href="javascript:void(0)" onClick={this.create.bind(this, "edit", record)}>编辑</a>
        <span className="ant-divider" />
        <a href="javascript:void(0)" onClick={this.roleModal.bind(this, record)}>分配</a>
        <span className="ant-divider" />
        <Popconfirm title="您是否要删除该角色?" data-id={record.key} onConfirm={this.del.bind(this, record.id)} okText="是" cancelText="否">
          <a href="javascript:void(0)">删除</a>
        </Popconfirm>
      </span>
    ),
  }];

  initData = () => {
    this.setState({ loading: true });
    Promise.all([api.get('/get'), api.get('/menu')]).then(([role, menu]) => {
      let roleData = [];
      let expandRows = [];
      if (role.data) {
        roleData = [...role.data];
        roleData.forEach(element => {
          element.key = element.id;
          element.value = element.id;
          element.title = element.name;
        });
        roleData = jsonToTree({
          json: roleData,
          keepChild: false
        });
        role.data.forEach((element => {
          expandRows.push(element.id);
        }));
      }
      let menuData = [];
      if (menu.data) {
        menuData = [...menu.data];
        menuData.forEach(function (element) {
          element.key = element.id;
          element.value = element.id;
          element.title = element.name;
        });
        menuData = jsonToTreeByRoot({
          rootId: "1",
          json: menuData,
          keepChild: false
        });
      }
      this.setState({
        loading: false,
        menuList: menu.data,
        roleList: role.data,
        expandRows: expandRows,
        resData: roleData,
        roleTree:roleData,
        menuTree: menuData
      });
    }).catch(e => {
      console.error(e);
    });
  }
  componentDidMount = () => {
    this.initData();
  }

  menuHasChildren = (id) => {
    if (this.state.menuList) {
      for (let i = 0; i < this.state.menuList.length; i++) {
        if (this.state.menuList[i].parentId && this.state.menuList[i].parentId == id) {
          return true;
        }
      }
    }
    return false;
  }

  roleHasChildren = (id) => {
    if (this.state.roleList) {
      for (let i = 0; i < this.state.roleList.length; i++) {
        if (this.state.roleList[i].parentId && this.state.roleList[i].parentId == id) {
          return true;
        }
      }
    }
    return false;
  }

  create = (type, record, event) => {
    if (type == "create") {
      if (record.id) {
        this.setState({
          title: "添加角色",
          record: {
            parentIds: record.parentIds || '' + (record.id + ',') || '',
            parentId: record.id || '',
            parentName: record.name || ''
          },
        });
      } else {
        this.setState({
          title: "添加角色",
          record: { parentName: "无上级节点" },
        });
      }
      this.open();
    } else {
      record.parentName = "无上级节点"
      this.state.roleList.forEach((element) => {
        if (element.id == record.parentId) {
          record.parentName = element.name
        }
      });
      this.setState({ loading: true });
      api.get('/roleMenu', { id: record.id }).then((data) => {
        const result = data.data || [];
        let arr = [];
        let all = [];
        result.forEach((element) => {
          all.push(element.menuId);
          if (!this.menuHasChildren(element.menuId)) {
            arr.push(element.menuId);
          }
        });
        this.open();
        this.setState({
          title: "修改角色",
          loading: false,
          checkedKeys: arr,
          checkedAllKeys: all,
          loadCheckedKeys: true,
          record: record,
        });
      });
    }
  }
  roleModal = (record)=>{
    this.setState({ loading: true });
    api.get('/roleManage', { id: record.id }).then((data) => {
      const result = data.data || [];
      let arr = [];
      let all = [];
      result.forEach((element) => {
        all.push(element.id);
        if (!this.roleHasChildren(element.id)) {
          arr.push(element.id);
        }
      });
      this.roleOpen();
      this.setState({
        roleTitle: "分配角色",
        loading: false,
        roleCheckedKeys: arr,
        roleCheckedAllKeys: all,
        roleLoadCheckedKeys: true,
        roleRecord: record,
      });
    });
  }

  roleOpen = ()=>{
    this.setState({
      roleShowModal: true,
      roleClearForm: false
    });
  }
  roleClose = ()=>{
    this.setState({
      roleShowModal: false,
      roleLoadCheckedKeys: false,
      roleClearForm: true
    });
  }
  roleOk = () => {
    this.roleClose();
  }
  open = () => {
    this.setState({
      showModal: true,
      clearForm: false
    });
  }
  close = () => {
    this.setState({
      showModal: false,
      loadCheckedKeys: false,
      clearForm: true
    });
  }
  ok = () => {
    this.close();
    this.initData();
  }
  del = (id, event) => {
    api.delete('/del', { id: id }).then((data) => {
      const result = data.data;
      if (result.code == 0) {
        Message.success('删除成功！');
        this.initData();
      } else {
        Message.error(result.message);
      }
    });
  }
  onexpand = (expanded, record) => {
    let expandRows = [...this.state.expandRows];
    if (!expanded) {
      let index = expandRows.indexOf(record.id);
      if (index > -1) {
        expandRows.splice(index, 1);
        this.setState({ expandRows: expandRows })
      }
    } else {
      expandRows.push(record.id);
      this.setState({ expandRows: expandRows })
    }
  }
  render() {
    return (
      <div>
        <Row style={{ marginBottom: '10px' }} type="flex" justify="start">
          <Col style={{ width: 'auto', lineHeight: '28px' }}>
            <Button type="primary" icon="plus" onClick={this.create.bind(this, "create")}>添加根角色</Button>
          </Col>
        </Row>
        <PanelBox>
          {
            <Table
              rowKey="id"
              columns={this.columns}
              dataSource={this.state.resData}
              expandedRowKeys={this.state.expandRows}
              onExpand={this.onexpand}
              loading={this.state.loading}
              pagination={this.state.pagination}
              defaultExpandAllRows={true} />
          }
        </PanelBox>
        <Modal
          title={this.state.title}
          visible={this.state.showModal}
          onCancel={this.close}
          wrapClassName="vertical-center-modal"
          width="800"
          style={{ height: 'auto' }}
          footer={null}
        >
          <WrappedRegistrationForm loadCheckedAllKeys={this.state.checkedAllKeys} loadCheckedKeys={this.state.loadCheckedKeys} clearForm={this.state.clearForm} ok={this.ok} checkedKeys={this.state.checkedKeys} menuTree={this.state.menuTree} record={this.state.record} close={this.close} />
        </Modal>
        <Modal
          title={this.state.roleTitle}
          visible={this.state.roleShowModal}
          onCancel={this.roleClose}
          wrapClassName="vertical-center-modal"
          width="800"
          style={{ height: 'auto' }}
          footer={null}
        >
        <ManageRoleForm loadCheckedAllKeys={this.state.roleCheckedAllKeys} loadCheckedKeys={this.state.roleLoadCheckedKeys} clearForm={this.state.roleClearForm} ok={this.roleOk} checkedKeys={this.state.roleCheckedKeys} roleTree={this.state.roleTree} record={this.state.roleRecord} close={this.roleClose} />
        </Modal>
      </div>
    );
  }
}
